package com.example.mywanandroid.home;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import com.example.mywanandroid.R;
import com.example.mywanandroid.home.business.GetData;
import com.example.mywanandroid.home.business.ParseData;
import com.example.mywanandroid.home.business.RecyclerViewCallBack;
import com.example.mywanandroid.home.business.ViewPagerCallBack;
import com.example.mywanandroid.home.ui.InitComponents;
import com.example.mywanandroid.util.GlobalLoading;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import java.util.List;

public class HomeFragment extends Fragment {
    private View root;
    private InitComponents initComponents;
    private ViewPager viewPager;
    private RecyclerView recyclerView;
    private RefreshLayout refreshLayout;
    public static final int UPDATE_VIEWPAGER = 1;
    public static final int UPDATE_RECYCLERVIEW = 2;
    private GlobalLoading homeLoading;
    //缓存数据
    private SharedPreferences.Editor editor;
    private SharedPreferences readCache;
    //缓存是否开启
    private boolean isCache = true;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            homeLoading.showLoadUi(false, 0);
            switch (msg.what) {
                case UPDATE_VIEWPAGER:
                    List<ViewPagerItem> data = (List<ViewPagerItem>) msg.obj;
                    if(data == null) {
                        //重新加载页面
                        homeLoading.showReloadUi(getActivity());
                        return;
                    }
                    initComponents.initViewPager(viewPager, data, getActivity());
                    break;
                case UPDATE_RECYCLERVIEW:
                    List<RecyclerViewItem> recList = (List<RecyclerViewItem>) msg.obj;
                    if(recList == null) {
                        //重新加载页面
                        homeLoading.showReloadUi(getActivity());
                        return;
                    }
                    initComponents.initRecyclerView(recyclerView, recList, getActivity());
                    break;
                default:
                    break;
            }
            homeLoading.showLoadUi(true, 0);
        }
    };

    public View onCreateView(@NonNull final LayoutInflater inflater,
                             final ViewGroup container, Bundle saveInstanceState) {
        Log.d("MyFragment", "onCreateView");
        root = inflater.inflate(R.layout.fragment_home, container, false);
        initComponents = new InitComponents();
        viewPager = root.findViewById(R.id.home_view_pager);
        viewPager.setOffscreenPageLimit(4);
        recyclerView = root.findViewById(R.id.home_recyclerview);
        refreshLayout = root.findViewById(R.id.home_refreshLayout);
        homeLoading = root.findViewById(R.id.tel_login_loading_img);
        editor = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE).edit();
        readCache = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);

        //更新ViewPager
        GetData.getViewPagerData(new ViewPagerCallBack() {
            @Override
            public void onGetViewPagerData(String rawData) {
                Message msg = new Message();
                msg.what = UPDATE_VIEWPAGER;

                if(rawData != null) {
                    List<ViewPagerItem> urls = ParseData.parseViewPagerData(rawData);
                    msg.obj = urls;
                    //缓存数据
                    editor.putString("ViewPagerData", rawData);
                    editor.apply();
                }
                //加载缓存数据的方式
                else if(isCache){
                    String cacheData = readCache.getString("ViewPagerData", null);
                    List<ViewPagerItem> urls = ParseData.parseViewPagerData(cacheData);
                    msg.obj = urls;
                }
                handler.sendMessage(msg);
            }
        });
        //初始化RecyclerView
        GetData.getRecyclerViewData(0, new RecyclerViewCallBack() {
            @Override
            public void onGetRecyclerViewData(String rawData) {
                Message msg = new Message();
                msg.what = UPDATE_RECYCLERVIEW;
                if(rawData != null) {
                    final List<RecyclerViewItem> list = ParseData.parseRecyclerViewData(rawData);
                    msg.obj = list;
                    //缓存数据
                    editor.putString("RecyclerViewData", rawData);
                    editor.apply();
                }
                //加载缓存数据的方式
                else if(isCache){
                    String cacheData = readCache.getString("RecyclerViewData", null);
                    List<RecyclerViewItem> list = ParseData.parseRecyclerViewData(cacheData);
                    msg.obj = list;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast toast = Toast.makeText(getActivity(), "请求失败，显示为缓存数据", Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    });
                }
                // 初始化下拉刷新和加载更多
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initComponents.initRefresh(refreshLayout, getActivity());
                    }
                });
                handler.sendMessage(msg);
            }
        });

        return root;
    }
}